package com.dsmbase.corp.project.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.dsmbase.corp.common.JdbcTemplateAdapter;
import com.dsmbase.corp.project.domain.ProjectID;

@Component
public class ProjectIDDao {

	private JdbcTemplate jdbcTemplate;
	
	private static final String SELECT_BY_ID_SQL = "select project_id, project_name from project_list where project_id = ?";
	private static final String SELECT_ALL_SQL = "select * from project_list";
	
	@Autowired
	private DataSource dataSource;
	
	@Autowired
	public void setDataSource(DataSource ds) {
		dataSource = ds;
		this.jdbcTemplate = new JdbcTemplateAdapter(dataSource);
	}
	
	public ProjectID getProjectID(String id) throws SQLException {
		Object[] params = new Object[] { id };
		ProjectID projectID = null;
		try {
			projectID = (ProjectID) jdbcTemplate.queryForObject(SELECT_BY_ID_SQL,
					params, new ProjectIDRowMapper());
		} catch (EmptyResultDataAccessException e) {
			throw new SQLException(e);
		}
		return projectID;
	}
	
	public List<ProjectID> getAllProjects() throws SQLException {
		List<ProjectID> list = null;
		list = jdbcTemplate.query(SELECT_ALL_SQL, new ProjectIDRowMapper());
		return list;
	}
	
	public class ProjectIDRowMapper implements RowMapper<ProjectID> {

		public ProjectID mapRow(ResultSet rs, int index) throws SQLException {
			ProjectID projectID = new ProjectID(rs.getString("project_id"), rs.getString("project_name"));
			return projectID;
		}

	}
	
}
